/**
 * 2017，thor.com，all rights reserved。
 * 
 * Project：		palmmall-core
 * Filename：	RentalReportHqlBuilder.java
 * Created：		2017年5月25日
 * Creator：		wolv
 */
package com.thor.palmmall.dao.rpt.shop;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.thor.commons.util.StringUtil;
import com.thor.palmmall.api.rpt.shop.RentalReportParam;

/**
 * @author wolv
 *
 */
public class RentalReportHqlBuilder {

	public Query build(RentalReportParam param) {
		StringBuffer sb = new StringBuffer();

		// select
		sb.append("select ");
		if (StringUtil.isNullOrBlank(param.getDimensionField()) == false)
			sb.append(param.getDimensionField() + ",");
		else
			sb.append("'-',");
		sb.append(" sum(" + param.getAggregationValueField() + ")");

		// from
		sb.append(" from " + PRental.class.getName());

		// where
		sb.append(" where 1=1 ");
		if (StringUtil.isNullOrBlank(param.getStoreId()) == false)
			sb.append(" and storeId = :storeId");
		if (param.getDate() != null) {
          sb.append(" and beginDate <= :date ");
          sb.append(" and endDate >= :date ");
        }
	    if (param.getBeginDate() != null)
	      sb.append(" and beginDate >= :beginDate ");
	    if (param.getEndDate() != null)
	      sb.append(" and beginDate <= :endDate ");


		// group by
		if (StringUtil.isNullOrBlank(param.getDimensionField()) == false)
			sb.append(" group by " + param.getDimensionField());
		else
			sb.append(" group by '-'");

		Query query = em.createQuery(sb.toString());
		if (StringUtil.isNullOrBlank(param.getStoreId()) == false)
			query.setParameter("storeId", param.getStoreId());
		if (param.getDate() != null)
          query.setParameter("date", param.getDate());

		if (param.getBeginDate()!= null){
		  query.setParameter("beginDate", param.getBeginDate());
		}
		if(param.getEndDate() != null){
		  query.setParameter("endDate", param.getEndDate());
		}
		
		return query;
	}

	public static RentalReportHqlBuilder getInstance() {
		if (instance == null)
			instance = new RentalReportHqlBuilder();
		return instance;
	}

	private static RentalReportHqlBuilder instance;

	private RentalReportHqlBuilder() {
	}

	@PersistenceContext(unitName = "${thor-webui-core.persistent-unit}")
	protected EntityManager em;
}
